from django.shortcuts import render,redirect
from webresource.models import webresource
import subprocess

def index(request):
    return render(request, "index.html")

def create(request):
    if request.method == "GET":
        return render(request, "create.html")
    else:
        webname = request.POST["webname"]
        domainname = request.POST["domainname"]
        urladdress = request.POST["urladdress"]
        WR = webresource(webname=webname, domainname=domainname, urladdress=urladdress, webVPN=-1)
        WR.save()
        add_config(webname,urladdress,domainname)
        return redirect('/')

path = '/etc/nginx/sites-enabled/default'
nginx_path = "/etc/init.d/nginx"

def reload_nginx():
	subprocess.getoutput(nginx_path+" reload")
	return 1

def readConfig(path):
	fp = open(path)
	s = fp.read()
	fp.close()
	return s

def writeConfig(path, config):
	fw = open(path, 'w')
	fw.write(config)
	fw.close()

def add_config(upstream, server, servername):
	s = readConfig(path)
	uptext ="""
upstream  %s{
	server %s;
}"""%(upstream, server)
	servertext = """
server{
	listen 8080;
	server_name %s;
	location / {
		proxy_pass http://%s;
	}
}"""%(servername, upstream)
	config = uptext + '\n' + s + '\n' + servertext
#	print config
	writeConfig(path, config)
	reload_nginx()
